package cn.formaggie.controller.manage;


import cn.formaggie.annotation.CheckTwiceSubmit;
import cn.formaggie.controller.BaseController;
import cn.formaggie.entity.utilModel.PermissionIdWithBool;
import cn.formaggie.service.face.BackManageService;
import cn.formaggie.service.face.PermissionService;
import cn.formaggie.service.face.RolePermissionService;
import cn.formaggie.service.face.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/back/author")
public class AuthorManagerController extends BaseController {

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private BackManageService backManageService;

    @RequestMapping("/permission/get")
    public ModelAndView getPermissionsToView(@RequestParam(value = "roleId")Integer roleId,@RequestParam(value = "roleName")String roleName){
        ModelAndView mav=new ModelAndView();
        Map<String, List<PermissionIdWithBool>> permissions=permissionService.getPermissionsAndRoleSelected(permissionService.getPermissionsOrderByType(),backManageService.getPermissionsWithTypeByRoleId(roleId));
        mav.addObject("roleName",roleName);
        mav.addObject("roleId",roleId);
        mav.addObject("permissions",permissions);
        mav.setViewName("/backpage/manager/role/modifyPermissionOfRole");
        return mav;
    }

    @RequestMapping("/permission/modify")
    @CheckTwiceSubmit
    public ModelAndView modifyPermissionOfRole(@RequestParam(value = "roleId")Integer roleId,
                                         @RequestParam(value = "permissionIds",required = false)Integer permissionIds[]){
        ModelAndView mav=new ModelAndView();
        Boolean state=false;
        if(permissionIds==null){
            state=rolePermissionService.deleteAllPermissionForRole(roleId);
        }else {
            state = rolePermissionService.modifyRolePermission(roleId, Arrays.asList(permissionIds));
        }
        mav.addObject(STATE_MSG,state?"权限修改成功,下次登录时自动更新":"权限修改失败");
        mav.setViewName("/backpage/middleRedirect");
        return mav;
    }
}
